package com.ciwong.epaper.modules.me.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.TimeoutError;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.adapter.BookDeskAdapter;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.AddBookActivity;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.widget.MarginDecoration;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.utils.GsonUtil;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * 旧版书桌
 * Created by keepon on 2018/4/9.
 */

public class BookDeskFragment extends BaseFragment implements OnRefreshListener, View.OnClickListener {

    private BookDeskAdapter mBookDeskAdapter;
    private RecyclerView mRvBookDesk;
    private SwipeToLoadLayout mSwipeToLoadLayout;
    private List<EpaperInfo> mEpaperInfoList = new ArrayList<>();
    private static final String TAG = "BookDeskFragment";
    public static final int REQ_CODE_TO_BUY_SERVICE = 103;// 购买服务
    private RelativeLayout mRlCloseTips;
    private LinearLayout mLlTips, mLlNoNet;
    public static final String BOOK_DESK_TIPS_HIDE = "BOOK_DESK_TIPS_HIDE";
    private Button mBtnRetry;
    private RelativeLayout mRlDataContainer;


    public static BookDeskFragment newInstance() {
        BookDeskFragment fragment = new BookDeskFragment();
        return fragment;
    }

    public BookDeskFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_desk, container,
                false);
        findViews(view);
        initEvent();
        init();
        loadLocalData();
        registerBoradcastReceiver();
        return view;
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG);
        myIntentFilter.addAction(EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK);
        myIntentFilter.addAction(EpaperConstant.BROADCAST_SETBOOKS_HEAD);
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG.equals(intent.getAction())
                    || EpaperConstant.BROADCAST_SETBOOKS_HEAD.equals(intent.getAction())
                    || EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK.equals(intent.getAction())) {
                //延时一秒去网络请求，不然可能服务器那边没刷新
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getBookBooksFromNet();
                    }
                }, 1000);

            }
        }
    };

    private Handler mHandler = new Handler();

    private void unregisterReceiver() {
        if (mBroadcastReceiver != null)
            getActivity().unregisterReceiver(mBroadcastReceiver);
    }


    private void findViews(View view) {

        mRlCloseTips = view.findViewById(R.id.rl_close_tips);
        mLlTips = view.findViewById(R.id.ll_tips);
        mRvBookDesk = view.findViewById(R.id.swipe_target);
        mSwipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipe_toLoad_layout);
        mRlDataContainer = view.findViewById(R.id.listviewgroup);
        mLlNoNet = view.findViewById(R.id.ll_no_net);
        mBtnRetry = view.findViewById(R.id.btn_retry);

    }

    private void initEvent() {
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mRlCloseTips.setOnClickListener(this);
        mBtnRetry.setOnClickListener(this);
        mSwipeToLoadLayout.setLoadMoreEnabled(false);
    }

    private void init() {
        mRvBookDesk.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRvBookDesk.addItemDecoration(new MarginDecoration(getActivity()));
        mBookDeskAdapter = new BookDeskAdapter(R.layout.item_autonomic_book_case, mEpaperInfoList);
        mRvBookDesk.setAdapter(mBookDeskAdapter);


        mBookDeskAdapter.setOnItemClickListener(new BaseQuickOnItemClickListener() {
            @Override
            public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                EpaperInfo epaperInfo = mEpaperInfoList.get(position);
                if (null != epaperInfo) {
                    if (epaperInfo.getIsFree() == 1 || epaperInfo.getIsExpire() == 1) {
                        EpaperJumpManager.jumpToCatalog(R.string.go_back, mActivity,
                                epaperInfo,
                                IntentValue.JumpToBookCatalogType.FROM_DESK_BOOK, -1, epaperInfo.getServerId());
                    } else {
                        MeJumpManager.jumpBuyService(getActivity(), R.string.go_back, epaperInfo.getServerId(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    }
                }
            }
        });

    }

    private void loadLocalData() {
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_AUTONOMIC_STUDY_LIST,
                new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
                        getBookBooksFromNet();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                mEpaperInfoList = (List<EpaperInfo>) data;
                                //缓存到EApplication
                                EApplication.getInstance().setBookDeskEpaperInfos(mEpaperInfoList);
                                if (mEpaperInfoList != null && mEpaperInfoList.size() > 0) {
                                    if (mBookDeskAdapter.getFooterLayoutCount() > 0) {
                                        mBookDeskAdapter.removeAllFooterView();
                                    }
                                    mBookDeskAdapter.setNewData(mEpaperInfoList);
                                } else {
                                    View footerView = getFooterView();
                                    mBookDeskAdapter.addFooterView(footerView);
                                    mBookDeskAdapter.notifyDataSetChanged();
                                }
                                judgeShowTips();

                            }
                        } catch (Exception e) {

                        }
                        getBookBooksFromNet();
                    }
                });

    }

    private void judgeShowTips() {
        UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
        if (userInfoBase != null) {
            boolean isHideTips = ESystem.getSharedBoolean(BOOK_DESK_TIPS_HIDE + "_" + userInfoBase.getUserId(), false);
            if (!isHideTips && mEpaperInfoList != null && mEpaperInfoList.size() > 0) {
                mLlTips.setVisibility(View.VISIBLE);
            } else {
                mLlTips.setVisibility(View.GONE);
            }
        }
    }

    public void getBookBooksFromNet() {
        EpaperDao.getInstance().getAutonomicStudyBooks(EApplication.BRAND_ID, new BaseExtCallBack(mActivity) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                mSwipeToLoadLayout.setRefreshing(false);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                mSwipeToLoadLayout.setRefreshing(false);
                if (!NetworkUtils.isOnline() || data instanceof TimeoutError) {
                    if (mEpaperInfoList == null || mEpaperInfoList.size() == 0) {
                        mRlDataContainer.setVisibility(View.GONE);
                        mLlNoNet.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void success(Object data) {
                Log.e(TAG, "getBookBooksFromNet"+ GsonUtil.toJson(data));
                mSwipeToLoadLayout.setRefreshing(false);
                try {
                    mRlDataContainer.setVisibility(View.VISIBLE);
                    mLlNoNet.setVisibility(View.GONE);
                    List<EpaperInfo> autonomicStudyBeanList = (List<EpaperInfo>) data;
                    //缓存到EApplication
                    EApplication.getInstance().setBookDeskEpaperInfos(autonomicStudyBeanList);
                    if (autonomicStudyBeanList != null && autonomicStudyBeanList.size() >= 0) {
                        if (mBookDeskAdapter.getFooterLayoutCount() > 0) {
                            mBookDeskAdapter.removeAllFooterView();
                        }
                        mEpaperInfoList = autonomicStudyBeanList;
                        mBookDeskAdapter.setNewData(mEpaperInfoList);

                        // 保存自主学习本地数据
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_AUTONOMIC_STUDY_LIST,
                                (Serializable) autonomicStudyBeanList);

                        if (mEpaperInfoList != null && mEpaperInfoList.size() == 0 && mBookDeskAdapter.getFooterLayoutCount() == 0) {
                            View footerView = getFooterView();
                            mBookDeskAdapter.addFooterView(footerView);
                            mBookDeskAdapter.notifyDataSetChanged();
                        }

                        judgeShowTips();


                    }

                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
                    onRefresh();
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {
        if (NetworkUtils.isOnline()) {
            getBookBooksFromNet();
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    mSwipeToLoadLayout.setRefreshing(false);
                }
            }, 300);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_close_tips) {
            mLlTips.setVisibility(View.GONE);
            UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
            if (userInfoBase != null) {
                ESystem.setSharedBoolean(BOOK_DESK_TIPS_HIDE + "_" + userInfoBase.getUserId(), true);
            }
        } else if (id == R.id.btn_retry) {
            getBookBooksFromNet();
        }
    }


    private View getFooterView() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_empty_book_desk, (ViewGroup) mRvBookDesk.getParent(), false);
        Button btnGoWeishangCheng = view.findViewById(R.id.btn_jump_to_jiaofu);
        btnGoWeishangCheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EpaperJumpManager.jumpToAddBook(R.string.go_back, mActivity,
                        BookDeskFragment.this, RequestCode.BookDeskResquestCode.REQ_CODE_TO_ADD_BOOK_FROM_BOOK_DESK);
            }
        });
        return view;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

}
